package com.caishi.lkx.common;

import com.zzw.common.exception.BizRuntimeException;
import com.zzw.common.util.RotateImage;
import com.zzw.common.utils.MD5Util;
import com.caishi.lkx.common.config.DiamondConfig;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Service
public class SystemService {

    @Resource
    private DiamondConfig diamondConfig;

    public void aiCheck(boolean imageCheck, HttpServletRequest request, Long timestamp, String sign, String iv) {
        // 校验请求合法性
        if (imageCheck) {
            if (!RotateImage.codeCheckPass(request)) {
                throw new BizRuntimeException(CommonResultCode.needAiAuth);
            }
        } else {
            // 签名超过10秒无效
            if (timestamp == null || System.currentTimeMillis() - timestamp > 60 * 1000) {
                throw new BizRuntimeException(CommonResultCode.needAiAuth);
            }
            if (!MD5Util.MD5Encode(diamondConfig.getSmsSignKey() + timestamp + iv).equalsIgnoreCase(sign)) {
                throw new BizRuntimeException(CommonResultCode.needAiAuth);
            }
        }
    }

    public void aiCheck(boolean imageCheck, HttpServletRequest request, Long timestamp, String sign) {
        aiCheck(imageCheck, request, timestamp, sign, "");
    }
}
